//
//  YYTool.m
//  AFNetworking
//
//  Created by 余意 on 2018/7/3.
//

#import "YYTool.h"

@implementation YYTool

static YYTool * _instance = nil;

+ (instancetype)shareInstance
{
    static dispatch_once_t onceToken ;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc]init];
    });
    return _instance;
}

+ (NSDateFormatter *)shareDateFormatter
{
    static dispatch_once_t onceToken ;
    static NSDateFormatter * formatter;
    dispatch_once(&onceToken, ^{
        formatter = [[NSDateFormatter alloc] init];
    });
    return formatter;
}

#pragma mark - 根据基准字符串和长度来生成字符串
+ (NSString *)randomStringWithBaseString:(NSString *)baseString WithLength:(NSInteger)length;
{
    NSMutableString * randomString = [NSMutableString new];
    for (NSInteger i = 0 ; i < length ; i ++ )
    {
        NSInteger index = arc4random()%(baseString.length);
        NSString * str = [baseString substringWithRange:NSMakeRange(index, 1)];
        [randomString appendString:str];
    }
    return randomString;
}

+ (NSString *)randomNumberStringWithLength:(NSInteger)length
{
    return [self randomStringWithBaseString:@"0123456789" WithLength:length];
}

+ (NSString *)randomCharacterStringWithLength:(NSInteger)length
{
    NSString * baseString = @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    return [self randomStringWithBaseString:baseString WithLength:length];
}

+ (NSString *)randomStringWithLength:(NSInteger)length
{
    NSString * baseString = @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    return [self randomStringWithBaseString:baseString WithLength:length];
}

+ (NSString *)dateStringWithDate:(NSDate *)date WithFormart:(NSString *)formart
{
    NSDateFormatter * dateFormartter = [self shareDateFormatter];
    [dateFormartter setDateFormat:formart];
    NSString * dateString = [dateFormartter stringFromDate:date];
    return dateString;
}

+ (NSDate *)dateWithString:(NSString *)string WithFormart:(NSString *)formart
{
    NSDateFormatter * dateFormartter = [self shareDateFormatter];
    [dateFormartter setDateFormat:formart];
    NSDate * date = [dateFormartter dateFromString:string];
    return date;
}

+ (NSString *)nowTimeString
{
    return [self dateStringWithDate:[NSDate date] WithFormart:@"yyyyMMddHHmmss"];
}

+ (NSString *)nowTimeStamp
{
    NSTimeInterval a = [[NSDate date] timeIntervalSince1970] * 1000;
    NSString * timeString = [NSString stringWithFormat:@"%.f",a];
    return timeString;
}

+ (NSString *)UUID
{
    CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);
    CFStringRef cfString = CFUUIDCreateString(kCFAllocatorDefault, uuid);
    NSString * UUIDString = (__bridge NSString *)cfString;
    return UUIDString;
}

+ (NSString *)filterHTMLWithString:(NSString *)string
{
    NSScanner * scanner = [NSScanner scannerWithString:string];
    NSString * text = nil;
    while ([scanner isAtEnd] == NO) {
        [scanner scanUpToString:@"<" intoString:NULL];
        [scanner scanUpToString:@">" intoString:&text];
        string = [string stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:@""];
    }
    return string;
}

+ (BOOL)isNullWithString:(NSString *)string
{
    if (string == nil || string == NULL)
    {
        return YES;
    }
    
    if ([string isKindOfClass:[NSNull class]])
    {
        return YES;
    }
    
    if (![string isKindOfClass:[NSString class]])
    {
        return YES;
    }
    
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] == 0)
    {
        return YES;
    }
    
    return NO;
}

+ (BOOL)isNullWithArray:(NSArray *)array
{
    if (array == nil || array == NULL)
    {
        return YES;
    }
    
    if ([array isKindOfClass:[NSNull class]])
    {
        return YES;
    }
    
    if (![array isKindOfClass:[NSArray class]])
    {
        return YES;
    }
    
    if ([array count] == 0)
    {
        return YES;
    }
    return NO;
}

+ (BOOL)isNullWithDictionary:(NSDictionary *)dict
{
    if (dict == nil || dict == NULL)
    {
        return YES;
    }
    
    if ([dict isKindOfClass:[NSNull class]])
    {
        return YES;
    }
    
    if (![dict isKindOfClass:[NSDictionary class]])
    {
        return YES;
    }
    
    if ([dict count] == 0)
    {
        return YES;
    }
    
    return NO;
}

+ (NSDictionary *)dictionaryWithJSONString:(NSString *)JSONString
{
    if (!JSONString)
    {
        return  nil;
    }
    NSData * JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
    NSError * error;
    NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableContainers error:&error];
    if (error)
    {
        NSLog(@"JSON解析失败");
        return nil;
    }
    return dict;
}

+ (NSArray *)arrayWithJSONString:(NSString *)JSONString
{
    if (!JSONString)
    {
        return  nil;
    }
    NSData * JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
    NSError * error;
    NSArray * array = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableContainers error:&error];
    if (error)
    {
        NSLog(@"JSON解析失败");
        return nil;
    }
    return array;
}

+ (void)phoneWithMobile:(NSString *)mobile
{
    NSString * string = [NSString stringWithFormat:@"telprompt://%@", mobile];
    if (@available(iOS 10.0, *)) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:string] options:@{} completionHandler:nil];
    } else {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:string]];
    }
}


+ (UIImage *)fixOrientationWithImage:(UIImage *)img
{
    if (img.imageOrientation == UIImageOrientationUp)
    {
        return img;
    }
    
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (img.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, img.size.width, img.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, img.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, img.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        case UIImageOrientationUp:
        case UIImageOrientationUpMirrored:
            break;
    }
    
    switch (img.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, img.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, img.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        case UIImageOrientationUp:
        case UIImageOrientationDown:
        case UIImageOrientationLeft:
        case UIImageOrientationRight:
            break;
    }
    
    CGContextRef ctx = CGBitmapContextCreate(NULL, img.size.width, img.size.height,
                                             CGImageGetBitsPerComponent(img.CGImage), 0,
                                             CGImageGetColorSpace(img.CGImage),
                                             CGImageGetBitmapInfo(img.CGImage));
    CGContextConcatCTM(ctx, transform);
    
    switch (img.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,img.size.height,img.size.width), img.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,img.size.width,img.size.height), img.CGImage);
            break;
    }
    
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    
    return img;
}

+ (UIImage *)imageWithColor:(UIColor *)color WithSize:(CGSize)size
{
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

+ (CGFloat)getWidthWithString:(NSString *)string
                     WithFont:(UIFont *)font
                   WithHeight:(CGFloat)height
{
    CGSize size = CGSizeMake(MAXFLOAT, height);
    NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    NSDictionary * attributes = @{NSFontAttributeName:font,NSParagraphStyleAttributeName:paragraphStyle.copy};
    CGRect rect = [string boundingRectWithSize:size options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading) attributes:attributes context:nil];
    return ceilf(rect.size.height);
}

+ (CGFloat)getHeightWithString:(NSString *)string
                      WithFont:(UIFont *)font
                     WithWidth:(CGFloat)width
{
    CGSize size = CGSizeMake(width, MAXFLOAT);
    NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    NSDictionary * attributes = @{NSFontAttributeName:font,NSParagraphStyleAttributeName:paragraphStyle.copy};
    CGRect rect = [string boundingRectWithSize:size options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading) attributes:attributes context:nil];
    return ceilf(rect.size.width);
}

@end
